<template>
  <div>
    <div
      style="padding-top: 30px"
      v-if="showSearch"
      :class="{
        'enter-level flipInX': showSearch,
      }"
    >
      <el-form :inline="true" :model="searchFrom" class="demo-form-inline">
        <el-form-item label="分类名称">
          <el-input
            v-model="searchFrom.name"
            placeholder="请输入分类名称"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit" :icon="Search">
            搜索
          </el-button>
          <el-button type="info" @click="reset" :icon="Refresh">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div style="padding: 30px">
      <div
        style="
          padding-bottom: 20px;
          display: flex;
          justify-content: space-between;
        "
      >
        <div>
          <el-button :icon="Plus" type="success" @click="insertOne"
            >新增</el-button
          >
          <el-button
            :icon="Delete"
            type="danger"
            @click="batchDelType()"
            :disabled="isBatch"
            >删除</el-button
          >
        </div>
        <div>
          <el-button
            :icon="Search"
            circle
            @click="showSearch = !showSearch"
          ></el-button>
          <el-button :icon="Refresh" circle @click="reset"></el-button>
        </div>
      </div>
      <el-table
        ref="multipleTableRef"
        :data="dataList"
        style="width: 100%"
        height="600"
        row-key="id"
        :tree-props="{ children: 'list', checkStrictly: true }"
        @selection-change="handleSelectionChange"
        v-loading="dataLoding"
      >
        <el-table-column type="expand">
          <template #default="props">
            <div>
              <div
                class="flex gap-2"
                style="padding: 10px 0"
                v-if="props.row.list.length > 0"
              >
                <el-tag
                  v-for="tag in props.row.list"
                  :key="tag.id"
                  :class="{ activeTag: selectTag.indexOf(tag.id) !== -1 }"
                  :disable-transitions="false"
                  @click="onChooseTag(tag.id)"
                  class="pointer"
                  style="margin-right: 10px; margin-bottom: 10px"
                >
                  {{ tag.name }}
                </el-tag>
                <el-button
                  size="small"
                  :icon="Delete"
                  type="text"
                  @click="batchDelTag(1)"
                >
                  删除
                </el-button>

                <el-button-group class="ml-4">
                  <el-button size="small" type="text" @click="batchDelTag(2)">
                    {{ batchDelTitle }}
                  </el-button>
                  <el-button
                    type="text"
                    size="small"
                    v-if="delTagStep === 1"
                    @click="tagDelCancel"
                  >
                    取消
                  </el-button>
                </el-button-group>
              </div>
              <div v-else>
                <div
                  style="
                    width: 100%;
                    text-align: center;
                    padding: 10px 0;
                    color: #c1c1c1;
                  "
                >
                  No Data
                </div>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column type="selection" :selectable="selectable" width="55" />
        <el-table-column
          type="index"
          :index="indexMethod"
          label="编号"
          width="105"
        />
        <el-table-column property="name" label="分类名称" />
        <el-table-column label="创建时间" width="200">
          <template #default="scope">{{ scope.row.createTime }}</template>
        </el-table-column>
        <el-table-column label="操作" fixed="right" width="300">
          <template #default="scope">
            <el-button @click="oper(scope.row, 1)" type="text" :icon="EditPen">
              修改
            </el-button>

            <el-popconfirm
              confirm-button-text="确定"
              cancel-button-text="取消"
              :icon="InfoFilled"
              icon-color="#626AEF"
              title="确定要删除该分类吗？"
              @confirm="oper(scope.row.id, 2)"
            >
              <template #reference>
                <el-button type="text" :icon="Delete"> 删除 </el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 10px">
        <el-pagination
          :hide-on-single-page="true"
          background
          layout="prev, pager, next"
          :total="page.total"
          :page-size="page.size"
          :page-count="page.pages"
          @current-change="changePage"
          :pager-count="15"
        />
      </div>
    </div>
  </div>
  <add-type ref="addTypeRef" @common="saveType"></add-type>

  <el-dialog
    v-model="dialogVisible"
    title="注意"
    width="500"
    :before-close="tagDelCancel"
  >
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="tagDelCancel">取消</el-button>
        <el-button type="primary" @click="batchDel"> 确定 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import request from "@/assets/js/request";
import { ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import addType from "@/components/type/add-type.vue";
import {
  Search,
  Refresh,
  EditPen,
  Delete,
  Plus,
} from "@element-plus/icons-vue";

const showSearch = ref(true);
const dataLoding = ref(false);
const searchFrom = ref({
  name: "",
  pageSize: 20,
  pageNum: 1,
});
// 选择tag
const selectTag = ref([]);
const dialogVisible = ref(false);
// 记录当前批量删除tag的步骤
const delTagStep = ref(0);
const batchDelTitle = ref("批量删除");
const addTypeRef = ref();
const selectable = ref();
const dataList = ref([]);
const isBatch = ref(true);
const selectKey = ref([]);
const page = ref({
  size: 20,
  num: 1,
  pages: 1,
  total: 0,
});

const indexMethod = (index) => {
  return index + 1;
};
//获取数据
const getDataList = () => {
  dataLoding.value = true;
  searchFrom.value.pageSize = page.value.size;
  searchFrom.value.pageNum = page.value.num;
  request
    .post("/type/page", searchFrom.value)
    .then((res) => {
      if (res.code === 200) {
        dataList.value = res.data.records;
        page.value.size = res.data.size;
        page.value.total = res.data.total;
        page.value.pages = res.data.pages;
        page.value.num = res.data.current;
      } else {
        ElMessage.error(res.msg);
      }
      dataLoding.value = false;
    })
    .catch((err) => {
      ElMessage.error(err.message);
    });

  setTimeout(() => {
    dataLoding.value = false;
  }, 5000);
};

const saveType = (item) => {
  let formData = {
    id: item.id,
    name: item.name,
  };
  request
    .post("/type/save", formData)
    .then((res) => {
      if (res.code === 200) {
        ElMessage.success("操作成功");
        getDataList();
      } else {
        ElMessage.error("操作失败");
      }
    })
    .catch((err) => {
      ElMessage.error(err.message);
    });
};

// 选择tag
const onChooseTag = (id) => {
  if (delTagStep.value === 1) {
    // 批量删除
    if (selectTag.value.indexOf(id) === -1) {
      selectTag.value.push(id);
    } else {
      selectTag.value.splice(selectTag.value.indexOf(id), 1);
    }
  } else {
    selectTag.value = [id];
  }
};

// 新增数据
const insertOne = () => {
  addTypeRef.value.open(null, "添加分类");
};

// 数据操作
const oper = (key, type) => {
  if (type == 1) {
    addTypeRef.value.open(key, "修改分类");
    return;
  }
  selectKey.value = [key];
  batchDelType();
};

const changePage = (pageIndex) => {
  page.value.num = pageIndex;
  getDataList();
};

// 批量删除 tag
const batchDelTag = (type) => {
  if (type === 1) {
    // 单删
    batchDel();
  } else {
    // 批删
    if (delTagStep.value === 0) {
      selectTag.value = [];
      delTagStep.value = 1;
      batchDelTitle.value = "确定";
    } else {
      // 确定删除
      dialogVisible.value = true;
    }
  }
};

const batchDelType = () => {
  request
    .post("/type/remove", selectKey.value)
    .then((res) => {
      if (res.code === 200) {
        ElMessage.success("操作成功！");
        selectKey.value = [];
        getDataList();
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch((err) => {
      ElMessage.error(err.message);
    });
};

// 取消删除tag
const tagDelCancel = () => {
  selectTag.value = [];
  delTagStep.value = 0;
  dialogVisible.value = false;
  batchDelTitle.value = "批量删除";
};

// 确认批量删除tag
const batchDel = () => {
  request
    .post("/tag/batch-del", selectTag.value)
    .then((res) => {
      if (res.code === 200) {
        ElMessage.success("操作成功！");
        tagDelCancel();
        getDataList();
      } else {
        ElMessage.error(res.msg);
      }
    })
    .catch((err) => {
      ElMessage.error(err.message);
    });
};

const onSubmit = () => {
  if (searchFrom.value.name == "") {
    return;
  }
  getDataList();
};
const reset = () => {
  searchFrom.value = {
    name: "",
    pageSize: 20,
    pageNum: 1,
  };
  getDataList();
};

// 多选
const handleSelectionChange = (val) => {
  console.log(val);
  let arr = val.map((item) => item.id);
  selectKey.value = arr;
  if (selectKey.value.length > 0) {
    isBatch.value = false;
  } else {
    isBatch.value = true;
  }
};

onMounted(() => {
  getDataList();
});
</script>

<style scoped lang="scss">
.demo-form-inline .el-input {
  --el-input-width: 220px;
}

.demo-form-inline .el-select {
  --el-select-width: 220px;
}

.el-form-item__label {
  font-weight: bold;
}

.el-form {
  display: inline;
}

.activeTag {
  background: #fef0f0;
  border: #fde2e2 1px solid;
  color: #f67777;
}
</style>
